package logic

import (
	"context"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"month_zg6/rpc/models/mysql"
	"strconv"
	"time"

	"month_zg6/rpc/goods"
	"month_zg6/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderLogic {
	return &OrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderLogic) Order(in *goods.OrderRequest) (*goods.OrderResponse, error) {
	//err := redis.Rdb.SetNX(context.Background(), "goods", -1, time.Minute*1).Err()
	//if err != nil {
	//	return nil, err
	//}
	//err = redis.Rdb.Del(context.Background(), "goods").Err()
	//if err != nil {
	//	return nil, err
	//}
	atoi, err := strconv.Atoi(uuid.NewString())
	if err != nil {
		return nil, err
	}
	str := mysql.Order{
		OrderId:         atoi,
		UserId:          int(in.UserID),
		GoodsId:         int(in.GoodsID),
		GoodsName:       in.GoodsName,
		OrderDate:       time.Time{},
		ShippingAddress: in.ShippingAddress,
	}
	err = mysql.DB.Model(&mysql.Order{}).Create(&str).Error
	if err != nil {
		return nil, err
	}
	var good mysql.Goods
	err = mysql.DB.Model(&mysql.Goods{}).Where("id = ?", in.GoodsID).First(&good).Error
	if err != nil {
		return nil, err
	}
	if good.GoodsInventory <= 0 {
		return nil, err
	}
	as, err := strconv.Atoi(in.GoodsNum)
	if err != nil {
		return nil, err
	}
	str2 := mysql.Goods{
		Model: gorm.Model{
			ID: uint(in.GoodsID),
		},
		GoodsName:      in.GoodsName,
		GoodsInventory: good.GoodsInventory - as,
	}
	err = mysql.DB.Model(&mysql.Goods{}).Save(&str2).Error
	if err != nil {
		return nil, err
	}
	return &goods.OrderResponse{
		OrderId:         int64(atoi),
		UserId:          int64(str.UserId),
		GoodsId:         int64(str.GoodsId),
		GoodsName:       str.GoodsName,
		ShippingAddress: str.ShippingAddress,
		OtalAmount:      strconv.Itoa(int(str.TotalAmount)),
	}, nil
}
